package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"log"
	"time"
)

func main() {
	// 设置MongoDB连接地址
	uri := "mongodb://localhost:27017"
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	// 连接MongoDB
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri))
	if err != nil {
		panic(err)
	}

	defer func() {
		// 延迟释放连接
		if err = client.Disconnect(ctx); err != nil {
			panic(err)
		}
	}()

	// 检测MongoDB是否连接成功
	if err := client.Ping(ctx, readpref.Primary()); err != nil {
		panic(err)
	}
	fmt.Println("MongoDB连接成功！")

	// 获取numbers集合
	collection := client.Database("test").Collection("user1")

	// 插入一个文档
	/*res, err := collection.InsertOne(ctx, bson.D{{"name", "mary1"}, {"pw", "654321"}})
	id := res.InsertedID
	fmt.Println("新增文档Id=", id)*/

	filter := bson.D{{"name", "mary"}}
	update := bson.D{
		/*{"$inc", bson.D{ // 列值增长，在原有的基础上增加
			{"age", 12},
		}},*/
		/*{"$set", bson.D{ // Update document
			{"pw", "123"},
		}},*/
		{"$setOnInsert", bson.D{ // Addd on Insert only
			{"pw1", "123e3"},
		}},
	}
	updateResult, err := collection.UpdateOne(ctx, filter, update)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Matched %v documents and updated %v documents.\n", updateResult.MatchedCount, updateResult.ModifiedCount)

	// 查询文档
	res1, _ := collection.Find(ctx, bson.D{{"name", "mary"}})
	fmt.Println("查询所有结果", *res1)

}
